﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace SHomeWorkshop.LunarMind
{
    /// <summary>
    /// InsertTitlesQuicklyWindow.xaml 的交互逻辑
    /// </summary>
    public partial class InsertTitlesQuicklyWindow : Window
    {
        public InsertTitlesQuicklyWindow()
        {
            InitializeComponent();

            avalonEditor.Options.ShowTabs = true;
            avalonEditor.Options.ShowSpaces = true;
            avalonEditor.Options.ShowEndOfLine = true;
            avalonEditor.ShowLineNumbers = true;
            avalonEditor.Options.ConvertTabsToSpaces = false;

            avalonEditor.Text =
 @"//这行是注释，会被忽略
	示例新节点 1
		示例新节点 1－1
		示例新节点 1－2
	示例新节点 2
	示例新节点 3
//注释一定要顶格
		示例新节点 3－1
		示例新节点 3－2
			示例新节点 3－2－1
			示例新节点 3－2－2
		示例新节点 3－3
	示例新节点 4";

            this.Closing += InsertTitlesQuicklyWindow_Closing;
        }

        private void InsertTitlesQuicklyWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            e.Cancel = true;
            this.Hide();
        }

        private void AddButton_Click(object sender, RoutedEventArgs e)
        {
            //基本思路：
            //    1. 按 Tab 区分要批量添加的标题的层级
            //    2. 这些标题不支持换行。
            //    3. 要支持自动转换 LME 的树型文字表（但不支持备注——因为树型文字表的备注功能本来就不完善）
            //    4. 通过调用 InsertLowerLevelTitle() 和 InsertSameLevelTitle() 这两个静态方法来实现功能。
            //    5. 空行会被简单地忽略。

            #region 提醒用户是否正在向根标题执行
            var mst = Globals.MainWindow.MainSelectedTitle;
            if (mst == null)
            {
                var rt = Globals.MainWindow.RootTitle;
                if (rt != null)
                {
                    rt.SelectOnlySelf();
                    var result = MessageBox.Show("没选定任何标题，要向中心标题批量添加节点吗？", Globals.AppName, MessageBoxButton.OKCancel, MessageBoxImage.Warning);
                    if (result != MessageBoxResult.OK) return;
                }
                else
                {
                    MessageBox.Show("当前文档中连根标题都没有，无法执行操作！", Globals.AppName, MessageBoxButton.OK, MessageBoxImage.Warning);
                    return;
                }
            }
            else
            {
                if (mst.IsRootTitle)
                {
                    var result = MessageBox.Show("确定向中心标题批量添加节点吗？", Globals.AppName, MessageBoxButton.OKCancel, MessageBoxImage.Warning);
                    if (result != MessageBoxResult.OK) return;
                }
            }
            #endregion

            var lines = avalonEditor.Text.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);

            var validatedLinesCount = 0;

            Regex regex = new Regex(@"^\t{0,}");

            var previewTabCount = 0;

            #region 解决树型文字表转换问题
            Regex rgxTreeLineHeader = new Regex(@"^[!！][│　]{0,}[├└]{0,}(?!([ 　\t]*\{))");
            //对于树型文字表来说，由于Tab键用来调整层级，所以理论上不可能出现Tab符，
            //但由于要脱离LME环境，所以这里只得保留。

            for (int i = 0; i < lines.Length; i++)
            {
                if (lines[i].StartsWith("//")) continue;
                var headerMatch = rgxTreeLineHeader.Match(lines[i]);
                if (headerMatch.Success)
                {
                    lines[i] = new string('\t', headerMatch.Length) + lines[i].Substring(headerMatch.Length);
                }
            }
            #endregion

            #region 防止向根标题添加其它兄弟标题
            var hasNotStartWithTabLine = false;
            foreach (var line in lines)
            {
                if (line.StartsWith("//")) continue;

                if (line.StartsWith("\t") == false)
                {
                    hasNotStartWithTabLine = true; break;
                }
            }

            if (hasNotStartWithTabLine && Globals.MainWindow.MainSelectedTitle.IsRootTitle)   //根标题不允许添加同级标题
            {
                for (int i = 0; i <= lines.Length - 1; i++)
                {
                    if (lines[i].StartsWith("//")) continue;

                    lines[i] = "\t" + lines[i];
                }
            }
            #endregion

            var mi = new ModifingItem()
            {
                IsNeedRefreshTitleAndLinesLocation = true,
                ModifingName = "快速插入多层标题",
                OldSelectedTitleID = Globals.MainWindow.MainSelectedTitle.ID,
            };

            foreach (var line in lines)
            {
                if (line.StartsWith("//")) continue;

                var match = regex.Match(line);
                if (match.Success == false) continue;

                var newTabCount = match.Value.Length;
                if (newTabCount == previewTabCount)
                {
                    //添加同级标题
                    Commands.InsertSameLevelTitleCommand.InsertSameLevelTitle(line.Substring(match.Length), mi);
                }
                else if (newTabCount >= previewTabCount + 1)
                {
                    //添加下级标题，不允许跨级别
                    Commands.InsertLowerLevelTitleCommand.InsertLowerLevelTitle(line.Substring(match.Length), mi);
                    previewTabCount = previewTabCount + 1;
                }
                else if (newTabCount <= previewTabCount - 1)
                {
                    //返回上级添加标题
                    //这里头完全可能是不连续的
                    Title parentTitle = Globals.MainWindow.MainSelectedTitle;
                    for (int i = previewTabCount; i > newTabCount; i--)
                    {
                        if (parentTitle == null) break;
                        parentTitle = parentTitle.GetHigherLvelTitle();
                    }

                    if (parentTitle != null) parentTitle.SelectOnlySelf();
                    Commands.InsertSameLevelTitleCommand.InsertSameLevelTitle(line.Substring(match.Length), mi);
                    previewTabCount = newTabCount;
                }

                validatedLinesCount++;
            }

            if (validatedLinesCount <= 0)
            {
                MessageBox.Show("没有输入有效文本行，无法批量添加标题节点。", Globals.AppName, MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }
            else
            {
                Globals.MainWindow.Do(mi);
                Globals.MainWindow.IsModified = true;

                Globals.MainWindow.RefreshAutoNumber();
                Globals.MainWindow.RefreshTitleAndLinesLocation();
            }
        }

        private void Window_Activated(object sender, EventArgs e)
        {
            avalonEditor.Focus();
        }

        private void ConvertButton_Click(object sender, RoutedEventArgs e)
        {
            var lines = avalonEditor.Text.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);

            Regex rgxTreeLineHeader = new Regex(@"^[!！][│　]{0,}[├└]{0,}(?!([ 　\t]*\{))");
            //对于树型文字表来说，由于Tab键用来调整层级，所以理论上不可能出现Tab符，
            //但由于要脱离LME环境，所以这里只得保留。
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < lines.Length; i++)
            {
                var headerMatch = rgxTreeLineHeader.Match(lines[i]);
                if (headerMatch.Success)
                {
                    sb.Append(new string('\t', headerMatch.Length) + lines[i].Substring(headerMatch.Length) + "\r\n");
                }
            }

            avalonEditor.Text = sb.ToString();
        }
    }
}
